<template>
  <Combination
    ref="comCouponRef"
    class="com-coupon-wrap"
    :items="comItem"
    :comData="ruleForm.comData"
    :rules="comRules"
    :size="10"
    :isTips="true"
  ></Combination>
</template>

<script lang="ts" setup>
import Combination from '@/components/combination/combination.vue';
import { FormRules } from 'element-plus';
import { queryActivity } from '@/service/apis/market';
import { IS_INT } from '@/utils/verify';

interface Props {
  activityId?: string | any;
  labelWidth: number;
  postList?: boolean; // 是否请求优惠券列表
  couponsList?: any;
}
const prop = withDefaults(defineProps<Props>(), {
  activityId: '',
  labelWidth: 80,
  postList: true,
  couponsList: [] as any,
});

const comCouponRef = ref();

const optionsS = reactive({
  coupons: [] as any,
});

const setComOptions = () => {
  nextTick(() => {
    comCouponRef.value?.setOptions(0, 0, optionsS.coupons);
    comCouponRef.value?.setItemOption(optionsS.coupons, 0);
    if (prop.activityId) {
      ruleForm.comData?.forEach((item: any, index: number) => {
        comCouponRef.value?.setOptions(index, 0, optionsS.coupons);
        comCouponRef.value?.setValue(index, 'couponName', item.couponName);
        const cobj = optionsS.coupons.find(
          (temp: any) => temp.value === item.couponId
        );
        if (cobj) {
          comCouponRef.value?.setValue(index, 'count', cobj.count);
        }
      });
    }
  });
};
// 获取下拉优惠券
const getCouponList = () => {
  queryActivity({}).then((res: any) => {
    optionsS.coupons = res.map((item: any) => {
      return { label: item.name, value: item.id, count: item.restCount };
    });
    setComOptions();
  });
};

if (!prop.activityId && prop.postList) {
  getCouponList();
}

watch(
  () => prop.couponsList,
  (newVal, oldVal) => {
    if (!prop.postList) {
      optionsS.coupons = newVal;
      setComOptions();
    }
  },
  { immediate: true, deep: true }
);

const ruleForm = reactive({
  comData: [] as any,
});

const getCouponLabel = () => {
  let arr: any = [];
  for (let i = 0; i < 10; i++) {
    arr[i] = `优惠券${i + 1}`;
  }
  return arr;
};
const comItem = reactive([
  {
    comName: 'select',
    label: '优惠券1',
    labels: getCouponLabel(),
    labelWidth: prop.labelWidth,
    prop: 'couponId',
    width: 180,
    isOnly: true,
    tips: '当前库存：',
    tipKey: 'count',
    props: {
      remote: true,
      filterable: true,
      options: optionsS.coupons,
      change: (index: number, form: any) => {
        console.log('form----', form);
        const obj = form.data[index];
        if (obj.couponId) {
          const cobj = optionsS.coupons.find(
            (item: any) => item.value === obj.couponId
          );
          obj.count = cobj.count;
          obj.couponName = cobj.label;
        } else {
          obj.count = '';
          obj.couponName = '';
        }
        if (obj.couponCount) {
          comCouponRef.value?.validateField(`data.[${index}][couponCount]`);
        }
      },
    },
  },
  {
    comName: 'input',
    label: '',
    labelWidth: 0,
    prop: 'couponCount',
    width: 110,
    props: {
      append: '张',
      maxlength: 3,
      type: 'number',
      placeholder: '正整数',
    },
  },
]);

const checkCouponCount = (rule: any, value: any, callback: any) => {
  const index = rule.field.split('.[')[1].split(']')[0];
  const obj = comCouponRef.value?.getData();
  if (obj[index].couponId && Number(value) > Number(obj[index].count)) {
    callback(new Error('不能大于库存'));
  }
  callback();
};
const comRules = reactive<FormRules>({
  couponId: [
    { required: true, message: '请选择优惠券', trigger: ['blur', 'change'] },
  ],
  couponCount: [
    { required: true, message: '请输入数量', trigger: 'blur' },
    {
      pattern: IS_INT,
      message: '请输入正整数',
      trigger: 'blur',
    },
    { validator: checkCouponCount, trigger: 'blur' },
  ],
});

const getData = async () => {
  if (!comCouponRef.value) return;
  try {
    await Promise.all([comCouponRef.value.validate()]);
  } catch (fields: any) {
    for (const key in fields) {
      if (fields[key]) {
        comCouponRef.value.scrollToField(key);
        break;
      }
    }
    return false;
  }
  const resp = [] as any;
  const data = comCouponRef.value?.getData();
  data.forEach((item: any) => {
    resp.push({
      level: 0,
      qualifiedType: 0,
      couponId: item.couponId,
      couponCount: item.couponCount,
      couponName: item.couponName,
    });
  });
  return resp;
};

const setData = (data: any) => {
  ruleForm.comData = [];
  data.forEach((item: any) => {
    ruleForm.comData.push({
      couponId: item.couponId,
      couponCount: item.couponCount,
      couponName: item.couponName,
    });
  });
  if (prop.postList) {
    getCouponList();
  } else {
    setComOptions();
  }
};

defineExpose({
  getData,
  setData,
});
</script>

<style lang="scss" scoped>
.com-coupon-wrap {
  :deep(.el-form-item:first-child) {
    .el-form-item__content,
    .el-form-item__error {
      padding-left: 24px !important;
    }
  }
}
</style>